﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WeatheRx.Data;
using WeatheRx.DomainModel.Search;

namespace WeatheRx.Managers
{
    public interface IPriceManager
    {
        Price Get(int priceId);

        List<PriceHeaderModel> GetAll(int agencyId, bool includeOld = false);

        List<PriceHeaderModel> Search(string searchTerm, int agencyId, bool includeOld = false);

        void Store(Price price, bool deleteOld = true);
    }

    public class PriceManager : IPriceManager
    {
        public List<PriceHeaderModel> GetAll(int agencyId, bool includeOld = false)
        {
            List<PriceHeaderModel> result;
            using (var db = new HWAPEntities())
            {
                var prices = (includeOld)
                    ? db.Prices.Where(x => x.AgencyId == agencyId).ToList()
                    : db.Prices.Where(x => x.AgencyId == agencyId && x.EndDate == null).ToList();
                result = Mapper.Map<List<PriceHeaderModel>>(prices);
            }
            return result.OrderBy(x => x.ProcedureCode).ToList();
        }

        public List<PriceHeaderModel> Search(string searchTerm, int agencyId, bool includeOld = false)
        {
            return GetAll(agencyId, includeOld)
                .Where(x => (x.Description + " " + x.Name + " " + x.ProcedureCode).Contains(searchTerm))
                .OrderBy(x => x.Name.Contains(searchTerm))
                .ToList();
        }

        public Price Get(int priceId)
        {
            Price result;
            using (var db = new HWAPEntities())
            {
                result = db.Prices.First(x => x.PriceId == priceId);
            }
            return result;
        }

        public void Store(Price price, bool deleteOld = true)
        {
            using (var db = new HWAPEntities())
            {
                var oldPrices = db.Prices.Where(x => x.ProcedureCode == price.ProcedureCode && x.EndDate == null).ToList();
                oldPrices.ForEach(x =>
                {
                    x.Deleted = true;
                    x.EndDate = DateTime.Now;
                    x.DeletedBy = price.CreatedBy;
                });
                price.StartDate = DateTime.Now;
                db.Prices.Add(price);
                db.SaveChanges();
            }
        }
    }
}